<template>
  <!-- 捐赠详情卡片 -->
  <div v-if="openDetails" class="donation-detail-overlay">
    <div class="donation-card-container">
      <div class="donation-card">
        <!-- 卡片标题与状态 -->
        <div class="donation-card-header">
          <div class="header-left">
            <h2 class="donation-title">{{ donationDetail.oddNumber || '捐赠详情' }}</h2>
            <el-tag :type="getStatusType(donationDetail.status)" effect="dark" class="status-tag">
              {{ getDictLabel(donation_status, donationDetail.status) }}
            </el-tag>
          </div>
          <el-button type="text" @click="handleCloseDonation" class="close-btn">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
        
        <!-- 主要信息区域 -->
        <div class="donation-card-content">
          <!-- 捐赠信息部分 -->
          <div class="donation-info-section">
            <div class="donation-info-header">
              <div class="donor-info">
                <span class="info-label">捐赠人</span>
                <el-button link type="primary" @click="lookDonorDetail(donationDetail.donorId)" class="donor-link">
                  {{ donationDetail.donorName }}
                </el-button>
              </div>
              
              <div class="location-info" v-if="donationDetail.goodsShelves">
                <span class="info-label">位置</span>
                <span class="info-value">
                  {{donationDetail.loveHouseName+":"+ donationDetail.goodsShelves.deviceNumber + " : " + donationDetail.goodsShelves.shelfNumber }}
                </span>
              </div>
            </div>
            
            <div class="receiver-info" v-if="donationDetail.receiverName && donationDetail.receiverName != 'null'">
              <span class="info-label">取件人</span>
              <span class="info-value">{{ donationDetail.receiverName }}</span>
            </div>
          </div>
          
          <!-- 轮播图部分 -->
          <div class="donation-images-section">
            <h3 class="section-title">物品图片</h3>
            <div class="donation-images-carousel">
              <el-carousel 
                :interval="3000" 
                type="card" 
                height="180px" 
                autoplay
                indicator-position="outside"
                arrow="always"
              >
                <el-carousel-item v-for="(img, index) in imagesList" :key="index">
                  <div class="carousel-image-container" @click="previewImage(index)">
                    <el-image 
                      ref="imageRefs"
                      :src="img" 
                      fit="cover"
                      :preview-src-list="imagesList"
                      :initial-index="index"
                      class="carousel-image"
                      hide-on-click-modal
                      preview-teleported
                    >
                      <template #error>
                        <div class="image-error">
                          <el-icon><Picture /></el-icon>
                          <div>加载失败</div>
                        </div>
                      </template>
                      <template #placeholder>
                        <div class="image-placeholder">
                          <el-icon><Loading /></el-icon>
                        </div>
                      </template>
                    </el-image>
                    <div class="image-overlay">
                      <el-icon class="zoom-icon"><ZoomIn /></el-icon>
                      <span class="zoom-text">点击查看大图</span>
                    </div>
                  </div>
                </el-carousel-item>
              </el-carousel>
            </div>
          </div>
          
          <!-- 时间信息部分 -->
          <div class="donation-info-section">
            <h3 class="section-title">时间信息</h3>
            <div class="donation-info-grid time-grid">
              <div class="donation-info-item">
                <span class="info-label">申请时间</span>
                <span class="info-value">{{ parseTime(donationDetail.createTime, "{y}-{m}-{d} {h}:{m}:{s}") }}</span>
              </div>
              
              <div class="donation-info-item" v-if="donationDetail.storageTime && donationDetail.storageTime != 'null'">
                <span class="info-label">入库时间</span>
                <span class="info-value">{{ parseTime(donationDetail.storageTime, "{y}-{m}-{d} {h}:{m}:{s}") }}</span>
              </div>
              
              <div class="donation-info-item">
                <span class="info-label">最后操作时间</span>
                <span class="info-value">{{ donationDetail.updateTime }}</span>
              </div>
            </div>
          </div>
          
          <!-- 取消原因部分 -->
          <div class="donation-info-section" v-if="donationDetail.status == 1 && donationDetail.cancelReason != 'null' && donationDetail.cancelReason != ''">
            <h3 class="section-title">取消原因</h3>
            <div class="cancel-reason">
              {{ donationDetail.cancelReason }}
            </div>
          </div>
          
          <!-- 物品描述部分 -->
          <div class="donation-info-section">
            <h3 class="section-title">物品描述</h3>
            <el-input
              v-model="donationDetail.description"
              type="textarea"
              :rows="4"
              readonly
              class="description-textarea"
            />
          </div>
          
          <!-- 按钮区域 -->
          <div class="action-buttons" v-if="donationDetail.status == 0">
            <el-button
              type="success"
              @click="handlePass()"
              v-hasPermi="['manage:donation:edit']"
            >通过</el-button>
            <el-button
              type="danger"
              @click="handleReject()"
              v-hasPermi="['manage:donation:edit']"
            >拒收</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 引入用户详情对话框组件 -->
  <user-detail-dialog ref="userDetailRef" :schools="props.schools" />
  
  <!-- 拒收原因对话框 - 保留对话框形式，因为这是二级弹窗 -->
  <el-dialog
    title="拒收原因"
    v-model="openReject"
    width="500px"
    style="align-items: center"
    append-to-body
  >
    <!-- 拒收原因选择下拉框 -->
    <el-select
      v-model="rejectReason"
      placeholder="请选择拒收原因"
      style="width: 100%"
    >
      <el-option
        v-for="dict in reject_reason"
        :key="dict.value"
        :label="dict.label"
        :value="dict.value"
      ></el-option>
    </el-select>
    <!-- 确认,取消按钮 -->
    <el-col :span="24" style="text-align: right; margin-top: 10px">
      <el-button type="primary" @click="confirmReject()">确认</el-button>
      <el-button @click="cancelReject()">取消</el-button>
    </el-col>
  </el-dialog>
</template>
<script setup>
import { require } from "@/utils/validate";
import { getDonation,updateDonation } from "@/api/manage/donation";
import { computed, ref, watch } from 'vue';
import UserDetailDialog from "@/views/manage/user/components/UserDetailDialog.vue";
import { parseTime } from "@/utils/ruoyi";
import { Picture, Loading, ZoomIn, Close } from '@element-plus/icons-vue';
import { ElImageViewer } from 'element-plus';

const { proxy } = getCurrentInstance();
const { donation_status } = proxy.useDict("donation_status");
const { reject_reason } = proxy.useDict("reject_reason");
const emit = defineEmits(["handleCloseDonation", "refresh"]);

const props = defineProps({
  donationVisible: {
    type: Boolean,
    default: false,
  },
  donationDetail: {
    type: Object,
    default: () => ({}),
  },
  schools: {
    type: Array,
    default: () => [],
  },
});

// 用户详情组件引用
const userDetailRef = ref(null);
const openDetails = ref(false);
const openReject = ref(false);
const rejectReason = ref("");
const donationDetail = ref({});

// 计算属性：将逗号分隔的图片字符串转换为数组
const imagesList = computed(() => {
  if (!donationDetail.value || !donationDetail.value.images) return [];
  
  return donationDetail.value.images
    .split(',')
    .filter(img => img && img.trim() !== '')
    .map(img => img.trim());
});

// 监听捐赠物详情弹层显示/隐藏
watch(
  () => props.donationVisible,
  (val) => {
    openDetails.value = val;
  }
);

// 查看捐赠物详情 - 定义在这里，确保在defineExpose之前可用
function handleLookDetails(id) {
  if (!id) return;
  
  donationDetail.value = {};
  getDonation(id).then((response) => {
    donationDetail.value = response.data;
    openDetails.value = true;
  });
}

// 关闭货道弹窗
const handleCloseDonation = () => {
  openDetails.value = false;
  emit("handleCloseDonation");
};

// 查看捐赠者详情
function lookDonorDetail(id) {
  if (!id) return;
  userDetailRef.value?.handleLookDetails(id);
}

/** 通过审核按钮 */
function handlePass() {
  const donationId = donationDetail.value.id;
  if (!donationId) {
    proxy.$modal.msgError("捐赠详情ID不存在，请刷新页面重试");
    return;
  }

  updateDonation({
    id: donationId,
    status: 2,
  })
    .then((response) => {
      handleSuccessResponse();
    });
}

/** 拒收按钮相关逻辑 */
function cancelReject() {
  openReject.value = false;
  rejectReason.value = "";
}

function handleReject() {
  openReject.value = true;
  rejectReason.value = "";
}

function confirmReject() {
  const trimmedReason = (rejectReason.value || "").trim();
  if (!trimmedReason) {
    proxy.$modal.msgError("请输入有效的拒收原因");
    return;
  }

  const donationId = donationDetail.value.id;
  if (!donationId) {
    proxy.$modal.msgError("捐赠详情ID不存在，请刷新页面重试");
    return;
  }

  updateDonation({
    id: donationId,
    status: 1,
    cancelReason: trimmedReason,
  })
    .then((response) => {
      openReject.value = false;
      handleSuccessResponse();
    })
    .catch((error) => {
      handleError(error);
    });
}

/** 公共成功回调 */
function handleSuccessResponse() {
  handleCloseDonation();
  proxy.$modal.msgSuccess("操作成功");
  emit('refresh');
  resetDonationDetail();
}

/** 公共错误处理 */
function handleError(error) {
  console.error("接口调用失败:", error); // 记录错误日志
  proxy.$modal.msgError("操作失败，请稍后再试");
  resetDonationDetail();
}

/** 重置捐赠详情 */
function resetDonationDetail() {
  // 重置临时状态
  donationDetail.value = {};
}

/** 根据状态设置标签类型 */
const getStatusType = (status) => {
  if (status === 0) {
    return ""; // 对应蓝色
  } else if (status === 1) {
    return "danger"; // 对应红色
  } else if ([3, 4].includes(status)) {
    return "success"; // 对应绿色
  } else if (status === 2) {
    return "warning"; // 对应黄色
  } else if (status === 5) {
    return "info"; // 对应灰色
  }
  // 默认返回空字符串，避免无效状态影响样式
  return "";
};

/** 根据字典选项获取标签文本 */
const getDictLabel = (options, value) => {
  for (let i = 0; i < options.length; i++) {
    if (options[i].value == value) {
      return options[i].label;
    }
  }
};

// 图片预览相关
const imageRefs = ref([]);

// 手动触发图片预览
function previewImage(index) {
  // 创建一个临时的图片预览器
  const instance = ElImageViewer.createVNode({
    urlList: imagesList.value,
    initialIndex: index,
    zIndex: 3000,
    onClose: () => {
      document.body.removeChild(container);
    }
  });
  
  // 创建一个容器，并挂载图片预览器
  const container = document.createElement('div');
  document.body.appendChild(container);
  
  // 渲染图片预览器
  instance.component.render(container);
}

// 暴露方法给父组件
defineExpose({
  handleLookDetails
});
</script>

<style scoped>
/* 遮罩层样式 */
.donation-detail-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

/* 卡片容器 */
.donation-card-container {
  width: 580px;
  max-width: 90vw;
  max-height: 90vh;
  overflow: auto;
  animation: slide-in 0.3s ease;
}

@keyframes slide-in {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 卡片样式 */
.donation-card {
  border-radius: 12px;
  overflow: hidden;
  background-color: #fff;
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
}

/* 卡片头部 */
.donation-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: linear-gradient(135deg, #36d1dc, #5b86e5);
  color: white;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.donation-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.status-tag {
  margin: 0;
}

.close-btn {
  color: white;
  font-size: 20px;
}

/* 卡片内容 */
.donation-card-content {
  padding: 20px 24px 24px;
  max-height: calc(90vh - 80px);
  overflow-y: auto;
}

/* 信息区块 */
.donation-info-section {
  margin-bottom: 24px;
  background-color: #f8f9fb;
  border-radius: 10px;
  padding: 16px;
}

.donation-info-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.donor-info, .location-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.receiver-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.section-title {
  margin: 0 0 16px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  border-left: 4px solid #5b86e5;
  padding-left: 10px;
}

.donation-info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.time-grid {
  grid-template-columns: repeat(2, 1fr);
}

.donation-info-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-label {
  font-size: 13px;
  color: #909399;
}

.info-value {
  font-size: 14px;
  color: #303133;
}

.donor-link {
  margin: 0;
  padding: 0;
  height: auto;
  font-size: 14px;
}

/* 轮播图部分 */
.donation-images-section {
  margin-bottom: 24px;
}

.donation-images-carousel {
  width: 100%;
  margin: 10px 0;
}

.carousel-image-container {
  position: relative;
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f8f7fa;
  border-radius: 8px;
  overflow: hidden;
  cursor: zoom-in;
  transition: transform 0.2s;
}

.carousel-image-container:active {
  transform: scale(0.98);
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
  color: white;
  z-index: 2;
  pointer-events: none;
}

.carousel-image-container:hover .image-overlay {
  opacity: 1;
}

.zoom-icon {
  font-size: 24px;
  background-color: rgba(255, 255, 255, 0.8);
  color: #409EFF;
  padding: 8px;
  border-radius: 50%;
  margin-bottom: 8px;
}

.zoom-text {
  font-size: 12px;
  background-color: rgba(0, 0, 0, 0.6);
  padding: 2px 6px;
  border-radius: 4px;
}

.image-error, .image-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  color: #909399;
  font-size: 14px;
}

.image-error .el-icon, .image-placeholder .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 轮播图样式 */
:deep(.el-carousel__item) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-carousel__indicators) {
  margin-top: 10px;
}

:deep(.el-carousel__item--card) {
  width: 65%;
  height: 180px;
}

:deep(.el-carousel__mask) {
  opacity: 0.5;
}

:deep(.el-image__inner) {
  transition: transform 0.3s;
}

:deep(.el-image__inner:hover) {
  transform: scale(1.05);
  cursor: pointer;
}

/* 图片预览相关 */
:deep(.el-image-viewer__wrapper) {
  z-index: 3000;
}

:deep(.el-image-viewer__img) {
  max-width: 90vw;
  max-height: 90vh;
}

:deep(.el-image-viewer__close) {
  color: white;
}

:deep(.el-image-viewer__actions) {
  opacity: 1;
  background: rgba(0, 0, 0, 0.7);
}

/* 取消原因和描述 */
.cancel-reason {
  padding: 12px;
  background-color: white;
  border-radius: 6px;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.description-textarea {
  width: 100%;
}

/* 按钮区域 */
.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

@media (max-width: 600px) {
  .donation-info-header {
    flex-direction: column;
    gap: 12px;
  }
  
  .donation-info-grid, .time-grid {
    grid-template-columns: 1fr;
  }
}
</style>